<template>
    <a-card>
        <p style="font-weight: bold;font-size: 16px;">企业名称：{{ companyInfo.companyName }}</p>
        <a-form layout="inline">
            <a-row :gutter="24">
                <a-col :span="8">
                    <a-form-model-item label="日期">
                        <j-date v-model="queryParam.timeBegin" placeholder="开始日期" />
                        -
                        <j-date v-model="queryParam.timeEnd" placeholder="结束日期" />
                    </a-form-model-item>
                </a-col>
                <a-col :span="6">
                    <a-form-model-item label="商户">
                        <j-dict-select-tag v-model="queryParam.merchantId" dict-code="HC_MERCHANT,STORE_NAME,ID"
                            placeholder="请选择商户" @change="" style="width: 250px;" />
                    </a-form-model-item>
                </a-col>
                <a-col :span="10" style="line-height: 40px;">最新下单时间：{{ newOrderDataTime ? newOrderDataTime : '暂无下单'
                }}</a-col>
            </a-row>
            <a-row style="margin-top: 10px;">
                <a-col :span="24">
                    <a-button type="primary" @click="goBack" icon="rollback">返回上一页</a-button>
                    <!-- <a-button type="primary" @click="searchQuery" icon="search" style="margin-left: 8px">查询</a-button> -->
                    <a-button type="primary" @click="addNewStoreList()" icon="plus" style="margin-left: 8px">新增</a-button>
                    <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                    <!-- <a-button type="primary" @click="searchReset" icon="bars" style="margin-left: 8px">批量设置</a-button> -->
                </a-col>
            </a-row>
        </a-form>
        <div style="margin-top: 20px;">
            <a-table ref="table" size="middle" :scroll="{ x: true }" :bordered="false" rowKey="id" :columns="columns"
                :rowSelection="{
                    selectedRowKeys: selectedRowKeys,
                    onChange: onSelectChange,
                }" :dataSource="dataSource" :pagination="ipagination" class="j-table-force-nowrap"
                @change="handleTableChange">
                <template slot="htmlSlot" slot-scope="text">
                    <div v-html="text"></div>
                </template>
                <template slot="imgSlot" slot-scope="text,record">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                    <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt=""
                        style="max-width:80px;font-size: 12px;font-style: italic;" />
                </template>
                <template slot="fileSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
                    <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
                        下载
                    </a-button>
                </template>
                <span slot="action" slot-scope="text, record,index">
                    <!-- <a @click="showFormAlert('edit', record)">编辑店铺</a>
                    <a-divider type="vertical" /> -->
                    <a @click="showCopyModal('editDate', record)">编辑日期</a>
                    <a-divider type="vertical" />
                    <a @click="editFood(record)">编辑菜品</a>
                    <a-divider type="vertical" />
                    <a @click="showDownAlert(record.id)">自定义数据下载</a>
                    <a-divider type="vertical" />
                    <a @click="downAll(record.id)">下载</a>
                    <a-divider type="vertical" />
                    <!-- <a-popconfirm title="确定要创建副本吗?" @confirm="() => copyMenu(record.id)"> -->
                    <a @click="showCopyModal('copyMenu', record.id)">创建副本</a>
                    <a-divider type="vertical" />
                    <!-- </a-popconfirm> -->
                    <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                        <a>删除</a>
                    </a-popconfirm>
                </span>
            </a-table>
        </div>
        <store-add ref="storeAdd" @getStoreList="getStoreList"></store-add>
        <download-excel ref="downloadExcel"></download-excel>
        <a-modal v-model="visiable" :width="800" title="选择时间" @cancel="visiable = false" @ok="submit">
            <div style="display: flex;justify-content: flex-start;align-items: center;">
                选择日期：<j-date v-model="tempInfo.date" placeholder="菜单日期" @change="dateChange" />
            </div>
        </a-modal>
    </a-card>
</template>

<script>
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import storeAdd from './storeAdd.vue'
import DownloadExcel from './download.vue';

import moment from 'moment'
import { postAction, getAction } from '@api/manage'

function getDate(time) {
    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let day = time.getDate()
    return { year, month, day }
}

let nowDate = new Date();
let year = nowDate.getFullYear();
let month = nowDate.getMonth() + 1;
let maxDay;
if (month == 2) {
    if (year % 4 == 0 && year % 100 != 0 || year / 400 == 0) {
        maxDay = 29
    } else {
        maxDay = 38;
    }
} else {
    console.log('!!!!', month);
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        maxDay = 31;
    } else {
        maxDay = 30;
    }
}
console.log('maxDay', maxDay);
let timeBegin = `${year}-${month}-1`;
let timeEnd = `${year}-${month}-${maxDay}`;

export default {
    name: 'AntDesignVueJeecgCompanyDetail',
    mixins: [JeecgListMixin, mixinDevice],
    components: { storeAdd, DownloadExcel },
    props: ['companyInfo'],
    data() {
        let nowDate = new Date();
        let year = nowDate.getFullYear();
        let minute = nowDate.getMinutes();
        let day = nowDate.getDate();
        let date = year + '-' + minute + '-' + day + ' ';
        return {
            timeBegin,
            timeEnd,
            queryParam: {
                timeBegin,
                timeEnd
            },
            columns: [
                {
                    title: '#',
                    dataIndex: '',
                    key: 'rowIndex',
                    width: 60,
                    align: "center",
                    customRender: function (t, r, index) {
                        return parseInt(index) + 1;
                    }
                },
                {
                    title: '日期',
                    align: "center",
                    dataIndex: 'menuDisplayTime',
                },
                {
                    title: '上架店铺',
                    align: "center",
                    dataIndex: 'listingStore',
                },
                {
                    title: '操作人',
                    align: "center",
                    dataIndex: 'createBy'
                },
                {
                    title: '订单数量',
                    align: "center",
                    dataIndex: 'orderCount',
                    customRender: (t, r, index) => {
                        // if (new Date().getTime() < new Date(date + r.companyStartTime).getTime()) {
                        //     return '暂未开始'
                        // } else {
                        return t ? t : 0
                        // }
                    }
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    align: "center",
                    fixed: "right",
                    width: 147,
                    scopedSlots: { customRender: 'action' }
                }
            ],
            url: {
                list: "hc/hcCompanyDetail/list",
                delete: "hc/hcCompanyDetail/delete",
                deleteBatch: "hc/hcCompanyDetail/deleteBatch",
                // exportXlsUrl: "/hc/hcRider/exportXls",
                // importExcelUrl: "hc/hcRider/importExcel",
            },

            newOrderDataTime: '',

            type: '', //触发日期选择弹窗的类型，copyMenu:创建副本，editDate:修改日期
            visiable: false,
            tempInfo: {
                detailId: '', //点击创建副本临时存储的记录ID
                date: '',
            }
        };
    },
    mounted() {
    },
    methods: {
        moment,
        show(id) {
            this.queryParam.companyId = id;
            console.log('this.queryParam', this.queryParam);
            this.loadData();
            this.getNewOrderData();
        },
        async getNewOrderData() {
            let res = await getAction('/hc/hcCompanyFoodOrder/getCompanyOrderLatest', { companyId: this.queryParam.companyId });
            console.log('res84684', res);
            this.newOrderDataTime = res.result ? res.result.createTime : null;
        },
        goBack() {
            this.$emit('changeMode', 1)
        },
        loadData(arg) {
            if (!this.queryParam.companyId) {
                return;
            }
            if (!this.url.list) {
                this.$message.error("请设置url.list属性!")
                return
            }
            //加载数据 若传入参数1则加载第一页的内容
            if (arg === 1) {
                this.ipagination.current = 1;
            }
            var params = this.getQueryParams();//查询条件
            this.loading = true;
            getAction(this.url.list, params).then((res) => {
                if (res.success) {
                    //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                    this.dataSource = res.result.records || res.result;
                    if (res.result.total) {
                        this.ipagination.total = res.result.total;
                    } else {
                        this.ipagination.total = 0;
                    }
                    //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                } else {
                    this.$message.warning(res.message)
                }
            }).finally(() => {
                this.loading = false
            })
        },
        getTime(time) {
            return time ? this.moment(time, 'YYYY-MM-DD HH:mm') : null
        },
        editFood(record) {
            let params = JSON.parse(JSON.stringify(record));
            params.siteId = this.companyInfo.siteId;
            this.$emit('changeMode', 3, params);
        },
        addNewStoreList() {
            this.$refs.storeAdd.show('add', this.companyInfo.siteId);
        },
        async getStoreList(record) {
            let { menuDisplayTime, merchantIds } = record;
            let params = {
                menuDisplayTime,
                companyId: this.companyInfo.id,
                merchantIds
            }
            let res = await getAction('hc/hcCompanyMerchantInfo/addMerchantInfo', params);
            console.log('新增res', res);
            if (res.success) {
                this.$message.success('菜单新建成功');
                this.loadData();
                this.$refs.storeAdd.cancel();
                return
            } else {
                this.$message.warning(res.message);
            }
        },
        /**
         * 展示日期modal
         * type：出发类型
         *  copyMenu:创建副本
         *  editDate:编辑日期
        */
        showCopyModal(type, record) {
            this.visiable = true;
            this.type = type;
            if (type == 'copyMenu') {
                this.tempInfo.detailId = record;
                this.tempInfo.date = '';
            } else if (type == 'editDate') {
                this.tempInfo = record;
                this.tempInfo.date = record.menuDisplayTime;
            }
        },
        submit() {
            this.type == 'editDate' ? this._editDate() : this.copyMenu();
        },
        dateChange(e) {
            console.log('e', e);
            this.tempInfo.date = e;
            this.$forceUpdate();
            console.log(this.tempInfo.date, '6365')
        },
        //创建副本
        async copyMenu() {
            let { detailId, date } = this.tempInfo;
            let res = await getAction('/hc/hcCompanyDetail/createTranscript', { detailId, date });
            console.log('res', res);
            if (res.success) {
                this.$message.success('副本创建成功');
                this.loadData();
                this.visiable = false;
            } else {
                this.$message.warning(res.message);
            }
        },
        //编辑日期
        async _editDate() {
            let params = Object.assign({}, this.tempInfo);
            params.menuDisplayTime = this.tempInfo.date;
            console.log('params', params);
            let res = await postAction('/hc/hcCompanyDetail/updateById', params);
            console.log('res', res);
            if (res.success) {
                this.$message.success('日期修改成功');
                this.loadData();
                this.visiable = false;
            } else {
                this.$message.warning(res.message);
            }
        },

        showDownAlert(id) {
            this.$refs.downloadExcel.show(id);
        },
        async downAll(detailId) {
            let fieldList = [
                {
                    username: '姓名'
                },
                {
                    pickupAddress: '取餐地址'
                },
                {
                    merchantName: '商户名称'
                },
                {
                    foodsName: '菜品'
                },
                {
                    cost: '金额'
                },
                {
                    remark: '备注'
                },
                {
                    department: '部门'
                },
                {
                    submissionTime: '提交时间'
                }
            ]
            let res = await postAction('/hc/hcCompanyFoodOrder/customExportXls', { fieldList, detailId })
            console.log('res', res);
            window.open(this.getImgView(res.result))
        }
    },
};
</script>

<style lang="scss" scoped></style>